package com.cf.web.servlet;
import com.alibaba.fastjson.JSONObject;
import com.cf.dao.CommentDao;
import com.cf.dao.entity.Comment;
import com.cf.dao.entity.User;
import com.cf.dao.impl.CommentDaoImpl;
import com.cf.web.util.RequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@WebServlet(name = "CommentServlet", value = "/comment/*")
public class CommentServlet extends HttpServlet {
    private  CommentDao commentDao = new CommentDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            switch (pathInfo) {
                case "/all":
                    selectUserCommentCount(req, res);
                    break;
                    case "/comment":
                        selectCommentByWorkId(req, res);
                        break;
                default:
                    res.sendError(HttpServletResponse.SC_NOT_FOUND, "Invalid endpoint");
            }
        } else {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing endpoint");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
        String path = req.getPathInfo();
        if ("/insertComment".equals(path)) {
            insertComment(req, res);
        }else {
            res.sendError(HttpServletResponse.SC_NOT_FOUND, "路径不存在");
        }
    }

    // 查询用户评论总数
    private void selectUserCommentCount(HttpServletRequest req, HttpServletResponse res) throws IOException {
        // 设置响应内容类型
        res.setContentType("application/json;charset=UTF-8");
        try {
            // 调用 DAO 查询用户评论总数
            List<User> commentCount = commentDao.selectUserCommentCount();
            ObjectMapper objectMapper = new ObjectMapper();
            // 构造响应结果
            String jsonResponse = objectMapper.writeValueAsString(commentCount);
            // 写入响应
            res.setStatus(HttpServletResponse.SC_OK);
            res.getWriter().write(jsonResponse);
        } catch (Exception e) {
            // 处理查询异常
            e.printStackTrace();
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            res.getWriter().write("{\"error\": \"Failed to fetch user comment count.\"}");
        }
    }
    //根据作品id查询评论
    private void selectCommentByWorkId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json; charset=UTF-8");
        // 获取 id 参数，并进行验证
        String idParam = request.getParameter("id");
        int workId = 0;
        if (idParam == null || idParam.isEmpty()) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "ID parameter is missing.");
            return;
        }
        try {
            workId = Integer.parseInt(idParam);
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid ID format.");
            return;
        }
        try {
            // 获取评论列表
            List<Comment> comments = commentDao.selectCommentByWorkId(workId);
            // 创建响应数据
            JSONObject result = new JSONObject();
            result.put("comments", comments);
            result.put("success", true);
            // 使用 ObjectMapper 直接将 result 转为 JSON 字符串并写入响应
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            String jsonResponse = objectMapper.writeValueAsString(result);

            // 返回 JSON 数据
            response.getWriter().write(jsonResponse);
            response.setStatus(HttpServletResponse.SC_OK);
        } catch (SQLException e) {
            // 处理数据库异常
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error occurred.");
            e.printStackTrace();
        }
    }
    //添加评论
    private void insertComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json; charset=UTF-8");
        JSONObject param = RequestUtil.getParam(request);
        JSONObject result = new JSONObject();

        // 获取请求参数
        String useridStr = param.getString("userid");
        String worksidStr = param.getString("worksid");
        String content = param.getString("comment");
        String date = param.getString("date");
        String score = param.getString("rating");
        System.out.println(score);

        // 参数校验
        if (useridStr == null || worksidStr == null || content == null || useridStr.isEmpty() || worksidStr.isEmpty()) {
            result.put("success", false);
            result.put("message", "参数错误");
            response.getWriter().write(result.toJSONString());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // 转换为数字
        int userid;
        int worksid;
        try {
            userid = Integer.parseInt(useridStr);
            worksid = Integer.parseInt(worksidStr);
        } catch (NumberFormatException e) {
            result.put("success", false);
            result.put("message", "无效的数字参数");
            response.getWriter().write(result.toJSONString());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        // 日志输出
        System.out.println("userid:" + userid + " worksid:" + worksid + " content:" + content + " date:" + date);

        // 插入评论
        try {
            // 如果需要验证日期格式，可以使用正则表达式或简单的Date格式转换
            if (date != null && !date.isEmpty()) {
                // 验证日期格式，如果需要使用更复杂的验证，请用正则或解析
                // 示例：DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                // LocalDate parsedDate = LocalDate.parse(date, formatter);
            }

            // 调用评论插入方法
            commentDao.insertComment(userid, content, worksid, date);
            commentDao.updateCommentCount(userid);

            if (score != null && !score.isEmpty()) {
                commentDao.updateScore(worksid, score, userid);
            }

            // 返回成功响应
            result.put("success", true);
            result.put("message", "评论成功");
            response.getWriter().write(result.toJSONString());
            response.setStatus(HttpServletResponse.SC_OK);
            System.out.println("评论成功");

        } catch (SQLException e) {
            // 处理数据库异常
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error occurred.");
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "数据库错误");
            response.getWriter().write(result.toJSONString());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            System.out.println("数据库错误");
        }
    }

}
